package com.example.beiwang;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.example.beiwang.model.Record;
import com.example.beiwang.tools.DateUtil;
import com.example.beiwang.tools.RecordLab;

import java.util.List;


/**
 * 首页fragment
 */
public class RecordListFragment extends Fragment {
    private static final String TAG = "RecordListFragment";//日志打印

    /**
     * Recyclerview的调用顺序：
     * 1、调用adapter的构造函数，获取模型层的数据集合
     * 2、调用adapter的getItemCount()方法，将数据集合的总条数传入进去。
     * 3、调用adapter的onCreateViewHolder()方法，获取列表项的布局，并把列表项布局交给viewholder(RecordListViewHolder)
     * 3、调用viewholder的构造函数，对列表项布局的内部控件进行初始化
     * 4、调用adapter的onBindViewHolder()方法,将具体的模型数据交给viewholder.bind()方法，由bind()方法来填充列表项的要展示的数据
     */
    private RecyclerView mRecordListRecyclerView;

    private Callbacks mCallbacks;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //布局封装器拿到recyclerview布局
        View view = inflater.inflate(R.layout.fragment_list_record, container, false);
        //通过id拿到recyclerview对象
        mRecordListRecyclerView = view.findViewById(R.id.record_list_recyclerview);
        //StaggeredGridLayoutManager是指定recyclerview的列表项布局方式，该布局是瀑布布局
        mRecordListRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        RecordListAdapter adapter = new RecordListAdapter();
        mRecordListRecyclerView.setAdapter(adapter);
        return view;
    }

    //负责获取模型层数据，发起列表项数据填充命令
    private class RecordListAdapter extends RecyclerView.Adapter<RecordListViewHolder> {

        private List<Record> mRecords;

        //在构造函数中获取模型层数据
        public RecordListAdapter() {
            mRecords = RecordLab.getLab(getActivity()).getRecords();
        }

        @NonNull
        @Override
        //首先拿到列表项布局，并传给viewholder
        public RecordListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //先获取布局封装器
            LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
            //布局封装器拿到列表项布局
            View itemView = layoutInflater.inflate(R.layout.record_item, parent, false);
            //把列表项的内部控件控制操作，拿给ViewHolder
            RecordListViewHolder viewHolder = new RecordListViewHolder(itemView);
            return viewHolder;
        }

        @Override
        //发起列表项数据填充命令
        public void onBindViewHolder(@NonNull RecordListViewHolder holder, int position) {
            Record record = mRecords.get(position);
            holder.bind(record);
        }

        @Override
        //获取数据集合总条数
        public int getItemCount() {
            return mRecords.size();
        }
    }




    //viewholder负责管理列表项的内部控件的初始化和数据填充
    private class RecordListViewHolder extends RecyclerView.ViewHolder {
        //列表项的标题控件
        private TextView mTitleTextView;
        //列表项的内容控件
        private TextView mContentTextView;
        //列表项的感悟控件
        private TextView mTextThinkingTextView;
        //列表项的日期控件
        private TextView mFinishDateTextView;
        //列表项的已完成控件
        private CheckBox mCompleteCheckbox;

        private Record mRecord;

        //itemview是dapter传过来的列表项布局的对象
        public RecordListViewHolder(@NonNull View itemView) {
            super(itemView);
            //初始化列表项的内部控件
            mTitleTextView = itemView.findViewById(R.id.record_item_title);
            mContentTextView = itemView.findViewById(R.id.record_item_content);
            mTextThinkingTextView = itemView.findViewById(R.id.record_item_text_thinking);
            mFinishDateTextView = itemView.findViewById(R.id.record_item_finish_date);
            mCompleteCheckbox = itemView.findViewById(R.id.record_item_completed);
            //绑定点击事件
            bindOnclickListener(itemView);
        }


        //由adpter的onBindViewHolder方法调用
        public void bind(Record record) {
            mRecord = record;
            //填充列表项内部控件的展示数据
            mTitleTextView.setText(record.getTitle());
            mContentTextView.setText(record.getContent());
            mTextThinkingTextView.setText(record.getTextThinking());
            mFinishDateTextView.setText(DateUtil.parseDate(record.getFinishDate()));
            mCompleteCheckbox.setChecked(record.isCompleted());
        }

        public void bindOnclickListener(View itemView) {
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i(TAG, "点击列表单元");
                    mCallbacks.onRecordSelect(mRecord.getId());
                }
            });
        }
    }


    /**
     * -------------------菜单设置------------------start
     * 1、加载菜单资源
     * 2、处理菜单按钮的逻辑
     * 3、手动设置菜单按钮的显示(在onCreate()方法中执行setHasOptionsMenu(true))
     * */

    /**
     * 1、加载菜单资源
     */
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_list_record, menu);
    }

    /**
     * 2、处理菜单按钮的逻辑
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        //判断点击的哪个按钮了
        switch (item.getItemId()) {
            case R.id.new_record:
                //菜单按钮点击后的跳转逻辑
                Log.i(TAG, "点击了新增按钮");
                mCallbacks.onNewRecord();
                return true;
            default:
                return true;
        }
    }

    /**-------------------菜单设置------------------end*/

    /**
     * -------------------页面跳转------------------start
     * 1、创建一个接口，名字Callbacks(回调),直接创建在当前fragment
     * 2、要让RecordListFragment的托管activity(RecordActivity),来执行页面跳转的代码
     * 3、让RecordActivity实现Callbacks接口
     * 4、在RecordListFragment中创建一个成员变量，指的就是Callbacks(mCallbacks)接口
     * 5、使用onAttach给mCallbacks赋值，onAttach传入的参数正好就是RecordActivity
     * 6、使用onDetach给mCallbacks重置。回到原始状态
     * 7、在点击菜单按钮时，执行mCallbacks.onNewRecord()
     */

    public interface Callbacks {
        //在新建备忘录的时候，触发
        void onNewRecord();

        /**
         * 在点击列表单元项时，触发
         *
         * @param recordId 代表列表单元的id
         */
        void onRecordSelect(int recordId);
    }

    /**
     * 当fragment与activity建立关联时调用
     */
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mCallbacks = (Callbacks) context;
    }

    /**
     * 当fragment与activity解除关联时调用
     */
    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    /**-------------------页面跳转------------------end*/

}